<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="危废名称" prop="wasteName">
                <el-input v-model="queryParams.wasteName" placeholder="请输入危废名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="批次号码" prop="batchNumber">
                <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号码" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="危废状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择危废状态">
                    <el-option v-for="dict in wasteFlowStatusList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="焚化日期">
                <el-date-picker v-model="daterangeIncinerateDate" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="操作者" prop="createBy">
                <el-input v-model="queryParams.createBy" placeholder="请输入操作者" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="incinerateDisabled" plain size="mini" @click="handleIncinerate" v-hasPermi="['business:incinerateHandle:add']">批量焚化</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:incinerateHandle:edit']">修改</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="danger" plain :disabled="revertDisabled" size="mini" @click="handleDelete" v-hasPermi="['business:incinerateHandle:remove']">批量撤销</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['business:incinerateHandle:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="incinerateHandleList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="焚化处置ID" align="center" prop="incinerateHandleId" v-if="false" />
            <el-table-column label="批次号码" align="center" prop="batchNumber" width="180" />
            <el-table-column label="状态" align="center" prop="status" width="100" :formatter="wasteFlowStatusFormat" />
            <el-table-column type="expand">
                <template slot-scope="props">
                    <keep-alive>
                        <waste-info-card :row="props.row" />
                    </keep-alive>
                </template>
            </el-table-column>
            <el-table-column label="危废名称" align="left" prop="wasteName" min-width="150" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="150" />
            <el-table-column label="危废重量" align="center" prop="wasteWeight" />
            <el-table-column label="出库日期" align="center" prop="outDate" width="180" />
            <el-table-column label="出库操作者" align="center" prop="outOperator" width="100" />
            <el-table-column label="焚化方式" align="center" prop="incinerateMethod" :formatter="incinerateMethodFormat" width="120" />
            <el-table-column label="焚化日期" align="center" prop="incinerateDate" width="180" />
            <el-table-column label="焚化操作者" align="center" prop="incinerateOperator" width="100" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.status === 45" size="mini" type="text" @click="handleIncinerate(scope.row)" v-hasPermi="['business:incinerateHandle:edit']">焚化</el-button>
                    <el-button v-if="scope.row.status === 56 && scope.row.overDay <= 7" size="mini" type="text" @click="handleDelete(scope.row)" v-hasPermi="['business:incinerateHandle:remove']">撤销</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改焚化处置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="焚化方式" prop="incinerateMethod">
                    <el-select v-model="form.incinerateMethod" placeholder="请选择焚化方式">
                        <el-option v-for="item in incinerateMethodList" :label="item.dictLabel" :key="item.dictValue" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="焚化日期" prop="incinerateDate">
                    <el-date-picker clearable size="small" v-model="form.incinerateDate" type="date" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择焚化日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listIncinerateHandle, getIncinerateHandle, delIncinerateHandle, addIncinerateHandle, updateIncinerateHandle, exportIncinerateHandle } from "@/api/business/incinerateHandle";
import WasteInfoCard from "@/views/business/wasteInfoCard";

import { mapActions, mapGetters } from "vuex";

export default {
    name: "IncinerateHandle",
    components: {
        WasteInfoCard
    },
    data() {
        return {
            //按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 焚化处置表格数据
            incinerateHandleList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 焚化日期范围
            daterangeIncinerateDate: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                wasteName: undefined,
                batchNumber: undefined,
                incinerateDate: undefined,
                createBy: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                incinerateMethod: [
                    { required: true, message: "焚化方式不能为空", trigger: "blur" }
                ],
                incinerateDate: [
                    { required: true, message: "焚化日期不能为空", trigger: "blur" }
                ],
            },
            // 处置方式字典
            wasteHandlerMethodList: [],
            // 焚化按钮禁用标志
            incinerateDisabled: true,
            // 批量撤回按钮禁用标志
            revertDisabled: true,
            // 焚化方式列表
            incinerateMethodList: [],
            minDateTimeMsec: 0,
        };
    },
    created() {
        this.getList();
        this.initDictData();
        this.getHandleMethodList();
        this.getIncinerateMethodList();
    },
    computed: {
        ...mapGetters(["wasteFlowStatusOptions"]),
        wasteFlowStatusList() {
            return this.wasteFlowStatusOptions.filter(item => parseInt(item.dictValue) === 45 || parseInt(item.dictValue) === 56);
        },
        pickerOptions() {
            const that = this;
            return {
                disabledDate: function (time) {
                    let curDate = (new Date()).getTime();
                    const sevenDayMsec = 7 * 24 * 3600 * 1000;
                    let beforeSevenDay = curDate - sevenDayMsec;
                    that.minDateTimeMsec = (that.minDateTimeMsec === 0 ? beforeSevenDay : that.minDateTimeMsec);
                    return time.getTime() > Date.now() || time.getTime() < that.minDateTimeMsec;;
                }
            }
        }
    },
    methods: {
        ...mapActions({
            initDictData: "initDataForWasteInfoCard",
        }),
        /** 查询焚化处置列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (null != this.daterangeIncinerateDate && '' != this.daterangeIncinerateDate) {
                this.queryParams.params["beginIncinerateDate"] = this.daterangeIncinerateDate[0];
                this.queryParams.params["endIncinerateDate"] = this.daterangeIncinerateDate[1];
            }
            listIncinerateHandle(this.queryParams).then(response => {
                this.incinerateHandleList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 获取焚化方式 */
        getIncinerateMethodList() {
            this.getDicts("incinerate_method").then((response) => {
                this.incinerateMethodList = response.data;
            });
        },
        /** 获取处置方式 */
        getHandleMethodList() {
            this.getDicts("waste_handler_method").then((response) => {
                this.wasteHandlerMethodList = response.data;
            });
        },
        // 处置方式字典翻译
        handleMethodFormat(row, column) {
            return this.selectDictLabel(this.wasteHandlerMethodList, row.handleMethod);
        },
        // 焚化方式字典翻译
        incinerateMethodFormat(row, column) {
            return this.selectDictLabel(this.incinerateMethodList, row.incinerateMethod);
        },
        // 危废状态字典翻译
        wasteFlowStatusFormat(row, column) {
            return this.selectDictLabel(
                this.wasteFlowStatusOptions,
                row.status
            );
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                incinerateHandleId: undefined,
                wasteId: undefined,
                wasteName: undefined,
                batchNumber: undefined,
                outWarehouseDetailId: undefined,
                incinerateDate: undefined,
                delFlag: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                remark: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeIncinerateDate = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.incinerateHandleId)
            const isOverSevenDay = selection.some(item => item.overDay > 7);
            this.outWarehouseDetailIds = selection.map((item) => item.outWarehouseDetailId);
            if (selection.length === 0) {
                this.incinerateDisabled = true;
                this.revertDisabled = true;
            } else {
                const incineratedCount = selection.filter((item) => item.status === 56).length;
                this.incinerateDisabled = incineratedCount > 0;
                const preIncinerateCount = selection.filter((item) => item.status === 45).length;
                this.revertDisabled = (preIncinerateCount > 0) || isOverSevenDay;
            }
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加焚化处置";
        },
        /** 焚化按钮操作 */
        handleIncinerate(row) {
            this.loading = true;
            let incinerateDate = "";
            let outWarehouseDetailIdList = [];
            if (row.outWarehouseDetailId) {
                outWarehouseDetailIdList.push(row.outWarehouseDetailId);
                incinerateDate = row.outDate;
            } else {
                outWarehouseDetailIdList = this.outWarehouseDetailIds;
                const incinerateDateArr = this.incinerateHandleList.filter(item => this.ids.indexOf(item.outWarehouseDetailId) !== -1).map(item => item.outDate);
                incinerateDateArr.sort().reverse();
                incinerateDate = incinerateDateArr[0];
            }
            if (incinerateDate) {
                this.minDateTimeMsec = Date.parse(`${incinerateDate} 00:00:00`);
            }

            this.loading = false;
            this.form = {
                outWarehouseDetailIdList: outWarehouseDetailIdList,
                incinerateDate: this.parseTime(new Date()),
                incinerateMethod: this.incinerateMethodList[0].dictValue,
            };
            this.open = true;
            this.title = "危废焚化";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const incinerateHandleId = row.incinerateHandleId || this.ids
            getIncinerateHandle(incinerateHandleId).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.title = "修改焚化处置";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.incinerateHandleId != null) {
                        updateIncinerateHandle(this.form).then(response => {
                            this.buttonLoading = false;
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addIncinerateHandle(this.form).then(response => {
                            this.buttonLoading = false;
                            this.msgSuccess("操作成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const incinerateHandleIds = row.incinerateHandleId || this.ids;
            this.$confirm('是否确认撤销?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.loading = true;
                return delIncinerateHandle(incinerateHandleIds);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.msgSuccess("撤销成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有焚化处置数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportIncinerateHandle(queryParams);
            }).then(response => {
                this.download(response.msg);
                this.exportLoading = false;
            }).catch(() => { });
        }
    }
};
</script>

<style>
.demo-table-expand {
    font-size: 0;
    padding: 0px 0px 0px 150px;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>